﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using ICSharpCode.SharpZipLib.Zip;

namespace TfsSpotlight.Starter
{
    //Bartłomiej Legiędź
    static class Program
    {
        [STAThread]
        static void Main()
        {
            try
            {
                bool restart = false;

                do
                {
                    InstallUpdate();

                    string tfsSpotlightExecutable = "TfsSpotlight.exe";
                    string tfsSpotlightWorkingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

                    var processStart = new ProcessStartInfo(tfsSpotlightExecutable);
                    processStart.WorkingDirectory = tfsSpotlightWorkingDirectory;
                    var application = Process.Start(processStart);

                    if (application != null)
                    {
                        application.WaitForExit();
                        restart = application.ExitCode == 1000;
                    }
                }
                while (restart);
            }
            catch (Exception e)
            {
                MessageBox.Show(Messages.MsgUnknownError, Messages.CaptionInitializationError,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);

                WriteTraceException(e);
            }
        }

        private static void InstallUpdate()
        {
            string updatePackageFile = "UpdatePackage.zip";
            if (!File.Exists(updatePackageFile)) return;

            var view = new AutoUpdateView();
            view.Show();
            Application.DoEvents();

            try
            {
                ExtractPackageContents(updatePackageFile, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

                File.Delete(updatePackageFile);
            }
            catch (UnauthorizedAccessException uae)
            {
                MessageBox.Show(
                    String.Format(Messages.MsgNoWriteRights, Environment.NewLine),
                    Messages.CaptionInitializationError,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);

                WriteTraceException(uae);
            }
            finally
            {
                view.Close();
            }
        }

        private static void WriteTraceException(Exception e)
        {
            Trace.WriteLine(String.Format(Messages.MsgTrace, Environment.NewLine, e.GetType(), e.Message, e.StackTrace));
        }

        private static void ExtractPackageContents(string packageLocation, string destination)
        {
            if (!Directory.Exists(destination))
                Directory.CreateDirectory(destination);

            using (var s = new ZipInputStream(File.OpenRead(packageLocation)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (fileName != String.Empty)
                    {
                        string destinationFileName = Path.Combine(destination, fileName);
                        using (FileStream streamWriter = File.Open(destinationFileName, FileMode.Create))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
